﻿using System.Collections.Generic;
using System.Windows.Input;
using Microsoft.Expression.Interactivity.Core;

namespace TheMovieDb.Example.ViewModels
{
    public class MoviesViewModel : ViewModelBase
    {
        private string _searchText;
        public string SearchText
        {
            get { return _searchText; }
            set { _searchText = value;
                RaisePropertyChanged("SearchText");
            }
        }

        private IEnumerable<TmdbMovie> _movies;
        public IEnumerable<TmdbMovie> Movies
        {
            get { return _movies; }
            set { _movies = value;
                RaisePropertyChanged("Movies");
            }
        }

        private TmdbMovie _selectedMovie;
        public TmdbMovie SelectedMovie
        {
            get { return _selectedMovie; }
            set { _selectedMovie = value;
                RaisePropertyChanged("SelectedMovie");
                if(value != null)
                {
                    IsBusy = true;
                    _api.GetMovieInfoAsync(value.Id);
                }
            }
        }

        private TmdbMovie _movie;
        public TmdbMovie Movie
        {
            get { return _movie; }
            set { _movie = value;
                RaisePropertyChanged("Movie");
            }
        }

        private bool _isBusy;
        public bool IsBusy
        {
            get { return _isBusy; }
            set { _isBusy = value;
                RaisePropertyChanged("IsBusy");
            }
        }

        public ICommand SearchCommand { get; set; }

        private readonly TmdbApi _api = new TmdbApi("");

        public MoviesViewModel()
        {
            SearchCommand = new ActionCommand(Search);

            _api.MovieSearchCompleted += ApiMovieSearchCompleted;
            _api.GetMovieInfoCompleted += ApiGetMovieInfoCompleted;
        }

        void ApiGetMovieInfoCompleted(object sender, TmdbMovieInfoCompletedEventArgs e)
        {
            Movie = e.Movie;
            IsBusy = false;
        }

        void ApiMovieSearchCompleted(object sender, TmdbMovieSearchCompletedEventArgs e)
        {
            Movies = e.Movies;
            IsBusy = false;
        }

        public void Search()
        {
            if (string.IsNullOrEmpty(SearchText))
                return;

            IsBusy = true;
            _api.MovieSearchAsync(SearchText);
        }
    }
}
